package org.snail.chat.service.impl;

import lombok.extern.log4j.Log4j;
import org.snail.common.dingding.auth.AuthHelper;
import org.snail.common.dingding.chat.ChatHelper;
import org.snail.constant.CommonConstant;
import org.snail.constant.GroupConstant;
import org.snail.employee.mapper.AddressMapper;
import org.snail.other.bean.GroupDO;
import org.snail.other.mapper.GroupMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Log4j
@Component
@PropertySource("classpath:context-datasource.properties")
public class ChainToChatOptionService {

    @Autowired
    private GroupMapper groupMapper;
    @Autowired
    private AddressMapper addressMapper;

    @Value("${server.online.flag}")
    private int normalFlag;

    public void doOpiton(GroupDO groupDO) {
        log.error("doOption:"+groupDO);
        if(null!=groupDO) {
            try {
                //每次最大更新人数
                int offsetLength = GroupConstant.ADD_USER_LIST_MAX_NUM;

                //1、修改2、新增
                if(1==groupDO.getSaveType()) {
                    log.error("Update GroupName: " + groupDO.getGroupName() + ", OwnerId: " + groupDO.getOwnerId() + ", ChatId : " + groupDO.getChatId()+ ", AddUserIds: " + groupDO.getAddUserIds() + ", DelUserIds: " + groupDO.getDelUserIds());
                    if (normalFlag == CommonConstant.SERVER_VERSION){

                        List<String> addUserIdList = groupDO.getAddUserIds();
                        List<String> delUserIdList = groupDO.getDelUserIds();
                        //如果跟更新人数大于限制，先创建群组再逐步更新
                        if((null!=addUserIdList && addUserIdList.size()>=offsetLength) || (null!=delUserIdList && delUserIdList.size()>=offsetLength)) {
                            subListUpdateChat(addUserIdList, delUserIdList, groupDO, offsetLength);
                        } else {
                            if(groupDO.getAddUserIds()==null){
                                groupDO.setAddUserIds(new ArrayList<>());
                            }
                            if(groupDO.getDelUserIds()==null){
                                groupDO.setDelUserIds(new ArrayList<>());
                            }
                            ChatHelper.updateChat(AuthHelper.getAccessToken(), groupDO.getChatId(), groupDO.getGroupName(), groupDO.getOwnerId(), groupDO.getAddUserIds(), groupDO.getDelUserIds());
                        }
                    }

                    groupMapper.updateGroup(groupDO);
                    if(null!=groupDO.getAddUserIds() && !groupDO.getAddUserIds().isEmpty()) {
                        addressMapper.insertBatchAddresssBydeptIdAndUserids(groupDO.getAddUserIds(), groupDO.getId(), new Date());
                    }
                    if(null!=groupDO.getDelUserIds() && !groupDO.getDelUserIds().isEmpty()) {
                        addressMapper.deleteAddressListByDingID(groupDO.getDelUserIds(), groupDO.getId(), new Date());
                    }

                } else if(2==groupDO.getSaveType()) {
                    log.error("Insert GroupName: " + groupDO.getGroupName() + ", OwnerId: " + groupDO.getOwnerId() + ", AddUserIds: " + groupDO.getAddUserIds());
                    String chatId = null;
                    if (normalFlag == CommonConstant.SERVER_VERSION) {
                        List<String> addUserIdList = groupDO.getAddUserIds();
                        //如果新增人数大于限制，先创建群组再逐步更新
                        if(null!=addUserIdList && addUserIdList.size()>=offsetLength) {
                            //先创建所有者一个人的群组
                            List<String> ownerList = new ArrayList<String>();
                            ownerList.add(groupDO.getOwnerId());
                            chatId = ChatHelper.createChat(AuthHelper.getAccessToken(), groupDO.getGroupName(), groupDO.getOwnerId(), ownerList);
                            groupDO.setChatId(chatId);
                            //分步骤更新
                            subListUpdateChat(addUserIdList, null, groupDO, offsetLength);
                        } else {
                            chatId = ChatHelper.createChat(AuthHelper.getAccessToken(), groupDO.getGroupName(), groupDO.getOwnerId(), groupDO.getAddUserIds());
                        }
                    } else {
                        chatId = "testId" + groupDO.getOwnerId();
                    }

                    if (!StringUtils.isEmpty(chatId)) {
                        groupDO.setChatId(chatId);
                        groupMapper.saveGroup(groupDO);
                        if(null!=groupDO.getAddUserIds() && !groupDO.getAddUserIds().isEmpty()) {
                            addressMapper.insertBatchAddresssBydeptIdAndUserids(groupDO.getAddUserIds(), groupDO.getId(), new Date());
                        }
                    }

                }
            } catch (Exception e) {
                log.error("同步失败 GroupName: " + groupDO.getGroupName() + ", OwnerId: " + groupDO.getOwnerId() + ", ChatId : " + groupDO.getChatId()+ ", AddUserIds: " + groupDO.getAddUserIds() + ", DelUserIds: " + groupDO.getDelUserIds(), e);
            }
        }
    }

    /**
     * 如果人数超过限制，就分批执行
     * @param addUserIdList
     * @param delUserIdList
     * @param offsetLength
     * @param groupDO
     */
    private static void subListUpdateChat(List<String> addUserIdList, List<String> delUserIdList, GroupDO groupDO, int offsetLength) throws Exception{
        //如果新增人数大于限制，先创建群组再逐步更新
        boolean continueFlag = true;
        boolean continueAddFlag = false, continueDelFlag = false;
        int addUserOffsetStart=0, delUserOffsetStart=0;
        int addUserOffsetEnd=addUserOffsetStart+offsetLength, delUserOffsetEnd=delUserOffsetStart+offsetLength;

        while (continueFlag) {
            //每次需要更新的对象
            List<String> needAddUserIdList=null, needDelUserIdList=null;

            if((null!=addUserIdList && addUserIdList.size()>addUserOffsetEnd)) {
                needAddUserIdList = addUserIdList.subList(addUserOffsetStart, addUserOffsetEnd);
                addUserOffsetStart = addUserOffsetEnd;
                addUserOffsetEnd += offsetLength;
            } else {
                continueAddFlag = true;
                //新增人员，超出范围时
                if(null!=addUserIdList) {
                    needAddUserIdList = addUserIdList.subList(addUserOffsetStart, addUserIdList.size());
                    addUserOffsetStart = addUserIdList.size();
                }
            }

            if((null!=delUserIdList && delUserIdList.size()>delUserOffsetEnd)) {
                needDelUserIdList = delUserIdList.subList(delUserOffsetStart, delUserOffsetEnd);
                delUserOffsetStart = delUserOffsetEnd;
                delUserOffsetEnd += offsetLength;
            } else {
                if(null!=delUserIdList) {
                    needDelUserIdList = delUserIdList.subList(delUserOffsetStart, delUserIdList.size());
                    delUserOffsetStart = delUserIdList.size();
                }
                continueDelFlag = true;
            }

            if(continueAddFlag && continueDelFlag) {
                continueFlag = false;
            }

            log.error("needAddUserIdList = " + needAddUserIdList + "needDelUserIdList = " + needDelUserIdList+"GroupDO."+groupDO);
            if(needAddUserIdList==null){
                needAddUserIdList = new ArrayList<>();
            }
            if(needDelUserIdList==null){
                needDelUserIdList = new ArrayList<>();
            }
            ChatHelper.updateChat(AuthHelper.getAccessToken(), groupDO.getChatId(), groupDO.getGroupName(), groupDO.getOwnerId(), needAddUserIdList, needDelUserIdList);
        }
    }

}
